import api from "api"
var app = getApp();
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
function format_number(n) {
  var b = parseInt(n).toString();
  var len = b.length;
  if (len <= 3) { return b; }
  var r = len % 3;
  return r > 0 ? b.slice(0, r) + "," + b.slice(r, len).match(/\d{3}/g).join(",") : b.slice(r, len).match(/\d{3}/g).join(",");
}
function validate(o) {
  if (o.phonenumber) {
    if (!(/^1[34578]\d{9}$/.test(o.phonenumber))) {
      return "您输入的电话号码有误";
    }
  }
  if (o.passworld) {
    var patrn = /([a-zA-Z0-9]|[._]){6,16}$/;
    if (!patrn.exec(o.passworld)) return "密码只能输入5-20个以字母开头、可带数字、“_”、“.”的字串"

  }
  if (o.repeatpass) {
    if (o.passworld != o.repeatpass) {
      return "两次输入的密码不一致";
    }
  }
  if (o.username) {
    var patrn = /^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}$/;
    if (!patrn.exec(o.passworld)) return "用户名只能输入5-20个以字母开头、可带数字、“_”、“.”的字串";
    return '';
  }
  if (o.identifycode) {

  }

  
  return "";
}
function isLogin(){

  console.log("判断有没有登陆");
  wx.getStorage({
    key: 'session',
    success: function(res) {
      console.log("已经登陆--");
      var app = getApp();

      app.globalData.openid = res.data;
    },
    fail:function(){
      console.log("未登录--");
      login();
    }
  })
}

function login(callback){
  // wx.getUserInfo({
  //   withCredentials:true,
  //   success:function(response){
  //     console.log("获取用户信息");
  //     console.log(response.data);
  //   }
  // });
  // debugger;
  wx.login({
    success: function(res) {
      console.log("登陆成功！");
      //将code存入数据库
      //获取openid
      wx.request({
        url: 'https://api.weixin.qq.com/sns/jscode2session',
        data:{
          appid: "wx5fc88ddc229a6285",
          secret: "aea12ba34a536ca17a0569c5a4cd8f13",
          js_code: res.code
        },
        success:function(res){
          // debugger;
          wx.request({
            url: api.login,
            data: {
              id: res.data.openid,
              phone: "1",
              hy: "1"
            },
            success: function (response) {
              // debugger;
              //-------------------------------------
              console.log("登陆信息已存入数据库");
              // app.globalData.userType="用户";

            },
            type: "POST",
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },

          });
          //存入缓存
          wx.setStorage({
            key: 'session',
            data: res.data.openid,
          });
          //存入全局变量
          var app = getApp();
          // debugger;
          app.globalData.openid = res.data.openid;
          console.log(app.globalData.openid);

          setTimeout(function () {
            wx.removeStorage({
              key: 'session',
              success: function (res) {
                console.log('请重新登陆');
              },
            });
          }, 3000);
        }
      })

     
      if(callback){
        callback();
      }
    },
    fail: function(res) {},
    complete: function(res) {},
  })
}
/**
 * 加星星
 */
function addStar(name){
  if(name == ""){
    return "";
  }
  var firstChar = name.slice(0,1);
  console.log(firstChar);
  var name2= firstChar ;
  for(var i = 0; i < name.length - 1; i++){
    name2 += "*";
  }
  return name2;
}
/**
 * 图片上传
 */
function uploadImage(cb){
  // debugger;
  wx.chooseImage({
    count: 1, // 默认9
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    success: function (res) {
      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
      var tempFilePaths = res.tempFilePaths;
      var str = tempFilePaths[0];
      wx.uploadFile({
        url: api.uploadImage,
        filePath: str,　//待上传的图片，由 chooseImage获得
        header: {
          "content-type": "multipart/form-data"
        },
        name: 'uploadFile',
        success: function (res) {
          cb(res);
        },
        fail: function (res) {
          console.log("addfood fail", res);
        }
      });
    },

  })
}
module.exports = {
  formatTime: formatTime,
  format_number: format_number,
  login: login,
  isLogin:isLogin,
  addStar: addStar,
  uploadImage: uploadImage,
  /**
   * 校验
   */
  validate:validate,
  /**
   * 发送验证码
   */
  sendIdentifyCode:function(phonenumber){
    wx.request({
      url: api.sendIdentifyCode,
      data:{
        phoneNum:phonenumber
      },
      method:"GET",
      success:function(response){
        console.log("发送验证码成功！");
        console.log(response);
      }
    })
  }
}
